package com.yanyeori.webtest.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 文件资源映射配置
 *
 * @author chenkuan
 * @since 2022/10/2 16:48
 */
//@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    private String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    private String domain;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //本地文件上传路径
        registry.addResourceHandler(localFilePrefix + "/**")
                .addResourceLocations("file:" + localFilePath + "/"
                        , "classpath:/META-INF/resources/"
                        , "classpath:/resources/"
                        , "classpath:/static/"
                        , "classpath:/public/");
    }

    /**
     * 开启跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路由
        registry.addMapping(localFilePrefix + "/**")
                // 设置允许跨域请求的域名
                .allowedOrigins("*")
                // 设置允许的方法
                .allowedMethods("GET");
    }

    public String getLocalFilePrefix() {
        return localFilePrefix;
    }

    public void setLocalFilePrefix(String localFilePrefix) {
        this.localFilePrefix = localFilePrefix;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getLocalFilePath() {
        return localFilePath;
    }

    public void setLocalFilePath(String localFilePath) {
        this.localFilePath = localFilePath;
    }
}